package com.line.myprojectservice.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.line.myprojectservice.Mapper.MessageMapper;
import com.line.myprojectservice.dto.MessageDto;
import com.line.myprojectservice.po.Message;
import com.line.myprojectservice.service.MessageService;
import com.line.myprojectservice.utils.RedisUtil;
import com.line.myprojectservice.vo.MessageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Resource
    MessageMapper messageMapper;


    @Override
    public void addMessage(MessageDto messageDto) {
        Message message = new Message();
        // 定义id唯一标识
        message.setMessageId(IdUtil.fastSimpleUUID());
        message.setMessageContent(messageDto.getMessageContent());
        message.setMessageUserid(messageDto.getMessageUserid());
        message.setMessageTime(DateUtil.now());
        if (messageDto.getMessageParentid() != null) message.setMessageParentid(messageDto.getMessageParentid());
        message.setMessageForeignid(messageDto.getMessageForeignid());
        messageMapper.addMessage(message);

        //新增的时候不放入redis，毕竟这又不是VO
        //更新数据库后删除缓存

        try {
            RedisUtil.delete("Message" + messageDto.getMessageForeignid());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteMessageById(String id) {
        messageMapper.deleteMessageById(id);

        RedisUtil.delete("Message" + id);

    }

    @Override
    public Object queryMessageById(String id) {

        try {
            String redisResult = RedisUtil.getString("Message" + id);
            if (redisResult != null) {
                return redisResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        List<MessageVo> messageVos = messageMapper.queryMessageById(id);
        for (MessageVo MessageVo : messageVos) {
            String parentId = MessageVo.getMessageParentid();
            messageVos.stream().filter(c -> c.getMessageId().equals(parentId)).findFirst().ifPresent(MessageVo::setParentMessage);
        }

        if (!messageVos.isEmpty()) {
            try {
                RedisUtil.setStrings("Message" + id, JSONUtil.toJsonPrettyStr(messageVos));
            } catch (Exception e) {
                log.info("存入redis异常:" + e.getMessage());
            }
        }

         return messageVos;
    }


}